<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="110px"
    >
      <el-form-item label="订单编号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="下单用户名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入下单用户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="下单用户手机号" prop="userPhone">
        <el-input
          v-model="queryParams.userPhone"
          placeholder="请输入下单用户手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="订单完成时间" prop="finishTime">
        <el-input
          v-model="queryParams.finishTime"
          placeholder="请输入订单完成时间"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="买家留言" prop="remark">
        <el-input
          v-model="queryParams.remark"
          placeholder="请输入买家留言/备注"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="下单时间" prop="createdTime">
        <el-date-picker
          clearable
          v-model="queryParams.createdTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择下单时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['order:orders:add']"
        >新增</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['order:orders:edit']"
          >修改</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['order:orders:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['order:orders:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="ordersList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="orderNo" />
      <el-table-column label="下单用户名称" align="center" prop="userName" />
      <el-table-column label="下单用户手机号" align="center" prop="userPhone" />
      <el-table-column
        label="订单折前总金额"
        align="center"
        prop="totalAmount"
      />
      <el-table-column
        label="订单折后总金额"
        align="center"
        prop="totalAmount"
      />
      <el-table-column label="实际支付金额" align="center" prop="payAmount" />
      <el-table-column label="订单完成时间" align="center" prop="finishTime" />
      <el-table-column label="订单取消时间" align="center" prop="cancelTime" />
      <el-table-column label="买家留言/备注" align="center" prop="remark" />
      <el-table-column
        label="下单时间"
        align="center"
        prop="createdTime"
        width="180"
      >
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['order:orders:remove']"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-operation"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['order:orders:goodsStatus']"
            >货物状态</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="handleShowGoodsDetail(scope.row)"
            v-hasPermi="['order:orders:goodsDetail']"
            >商品详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单主页对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="goodstatusopen"
      width="500px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="收货人姓名" prop="receiverName">
          <el-input
            v-model="form.receiverName"
            placeholder="请输入收货人姓名"
          />
        </el-form-item>
        <el-form-item label="收货人手机号" prop="receiverPhone">
          <el-input
            v-model="form.receiverPhone"
            placeholder="请输入收货人手机号"
          />
        </el-form-item>
        <el-form-item label="收货地址" prop="receiverAddress">
          <el-input
            v-model="form.receiverAddress"
            placeholder="请输入收货地址"
          />
        </el-form-item>
        <el-form-item label="物流单号" prop="shippingNo">
          <el-input v-model="form.shippingNo" placeholder="请输入物流单号" />
        </el-form-item>
        <el-form-item label="物流公司" prop="shippingCompany">
          <el-input
            v-model="form.shippingCompany"
            placeholder="请输入物流公司"
          />
        </el-form-item>
        <el-form-item label="发货时间" prop="shippingTime">
          <el-input v-model="form.shippingTime" placeholder="请输入发货时间" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 商品详情列表 -->
    <el-dialog
      :title="'商品详情 - 订单号：' + detailOrderNo"
      :visible.sync="detailOpen"
      width="1000px"
      append-to-body
    >
      <el-table :data="orderItemsDetailList" v-loading="detailLoading">
        <!-- <el-table-column label="商品ID" prop="goodId" align="center" /> -->
        <el-table-column label="商品名称" prop="goodName" align="center" />
        <el-table-column label="校区ID" prop="campusId" align="center" />
        <el-table-column
          label="商品原价"
          prop="goodOriginalPrice"
          align="center"
        />
        <el-table-column
          label="商品折后价"
          prop="goodDiscountPrice"
          align="center"
        />
        <el-table-column label="购买数量" prop="quantity" align="center" />
        <el-table-column label="小计金额" prop="totalprice" align="center" />
        <el-table-column
          label="分销员ID"
          prop="distributionId"
          align="center"
        />
        <el-table-column label="支付状态" prop="payStatus" align="center" />
        <el-table-column
          label="商品货物状态"
          align="center"
          prop="orderItemStatus"
        >
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.sys_commodity_status"
              :value="scope.row.orderItemStatus"
            />
          </template>
        </el-table-column>

        <!-- 新增操作列 -->
        <el-table-column label="操作" align="center" width="80">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="handleDeleteOrderItem(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listOrders,
  getOrders,
  delOrders,
  addOrders,
  updateOrders,
} from "@/api/order/orders";

import {
  listOrderItems,
  delOrderItems,
  selectArtGoodByGoodId,
} from "@/api/order/orderItems";
export default {
  name: "Orders",
  dicts: ["sys_commodity_status"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单主页表格数据
      ordersList: [],
      // 弹出层标题
      title: "",
      detailOpen: false, // 控制商品详情弹窗
      detailLoading: false, // 详情加载状态
      orderItemsDetailList: [], // 商品详情数据
      detailOrderNo: "", // 当前详情查看的订单编号
      // 是否显示弹出层
      goodstatusopen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNo: null,
        userName: null,
        userPhone: null,
        finishTime: null,
        cancelTime: null,
        remark: null,
        createdTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "下单用户ID不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询订单主页列表 */
    getList() {
      this.loading = true;
      listOrders(this.queryParams).then((response) => {
        this.ordersList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.goodstatusopen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        orderId: null,
        orderNo: null,
        userId: null,
        campusId: null,
        userName: null,
        userPhone: null,
        totalAmount: null,
        payAmount: null,
        receiverName: null,
        receiverPhone: null,
        receiverAddress: null,
        shippingNo: null,
        shippingCompany: null,
        shippingTime: null,
        finishTime: null,
        cancelTime: null,
        remark: null,
        isDeleted: null,
        createdTime: null,
        updatedTime: null,
        demo1: null,
        demo2: null,
        demo3: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.orderId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.goodstatusopen = true;
      this.title = "添加订单主页";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const orderId = row.orderId || this.ids;
      getOrders(orderId).then((response) => {
        this.form = response.data;
        this.goodstatusopen = true;
        this.title = "货物状态查看与修改 ";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.orderId != null) {
            updateOrders(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.goodstatusopen = false;
              this.getList();
            });
          } else {
            addOrders(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.goodstatusopen = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderIds = row.orderId || this.ids;
      this.$modal
        .confirm('是否确认删除订单主页编号为"' + orderIds + '"的数据项？')
        .then(function () {
          return delOrders(orderIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "order/orders/export",
        {
          ...this.queryParams,
        },
        `orders_${new Date().getTime()}.xlsx`
      );
    },
    // 点击“商品详情”按钮
    // handleShowGoodsDetail(row) {
    //   this.detailOpen = true;
    //   this.detailLoading = true;
    //   this.orderItemsDetailList = [];
    //   this.detailOrderNo = row.orderNo || "";
    //   // 查询该订单下的商品明细
    //   listOrderItems({ orderId: row.orderId, pageNum: 1, pageSize: 1000 })
    //     .then((response) => {
    //       this.orderItemsDetailList = response.rows || [];
    //       this.detailLoading = false;
    //     })
    //     .catch(() => {
    //       this.detailLoading = false;
    //     });
    // },
    handleShowGoodsDetail(row) {
      this.detailOpen = true;
      this.detailLoading = true;
      this.orderItemsDetailList = [];
      this.detailOrderNo = row.orderNo || "";
      // 查询该订单下的商品明细
      listOrderItems({ orderId: row.orderId, pageNum: 1, pageSize: 1000 })
        .then(async (response) => {
          const detailList = response.rows || [];
          console.log(detailList)
          // 并行查名字（提升性能，少量数据可以接受）
          await Promise.all(
            detailList.map(async (item) => {
              if (item.goodId) {
                try {
                  const res = await selectArtGoodByGoodId(item.goodId);
                  item.goodName = res.goodName || "-";
                } catch (e) {
                  item.goodName = "-";
                }
              } else {
                item.goodName = "-";
              }
            })
          );
          this.orderItemsDetailList = detailList;
          this.detailLoading = false;
        })
        .catch(() => {
          this.detailLoading = false;
        });
    },
    handleDeleteOrderItem(row) {
      this.$confirm("是否确认删除该商品明细？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delOrderItems(row.orderItemId).then(() => {
            this.$modal.msgSuccess("删除成功");
            // 重新加载商品详情
            this.handleShowGoodsDetail({
              orderId: row.orderId,
              orderNo: this.detailOrderNo,
            });
          });
        })
        .catch(() => {});
    },
  },
};
</script>
